package com.guoxin.jiyin.service.impl;

import com.guoxin.jiyin.service.BlockChainsService;
import com.guoxin.jiyin.utils.FabricHelper;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;


@Service

public class BlockChainsServiceImpl implements BlockChainsService {

    private static final Logger log = LogManager.getLogger(BlockChainsServiceImpl.class);

    @Autowired
    private Environment env;


    private static FabricHelper helper;

    @PostConstruct
    public void init() {
        log.info("init sdk config");
        helper = FabricHelper.getInstance();
        String config = "config/development/bcs-1-sdk-config.yaml";

        if (env.acceptsProfiles("test")) {
            config = "config/test/bcs-1-sdk-config.yaml";
        }

        if (env.acceptsProfiles("production")) {
            config = "config/production/bcs-1-sdk-config.yaml";
        }
        String certPath = this.getClass().getClassLoader().getResource(config).getPath();
        helper.setConfigCtx(certPath);
        helper = FabricHelper.getInstance();
    }

    public boolean write(String key, String value) {
       return helper.invokeBlockchain("write", new String[]{key, value});
    }

    @Override
    public String read(String key) {
        return helper.queryBlockchain("read", new String[]{key});
    }

//    @Override
//    public void Aes(String text) {
//
//        try {
//            // 生成key
//            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
//            keyGenerator.init(128);
//            SecretKey secretKey = keyGenerator.generateKey();
//            byte[] keybytes = secretKey.getEncoded();
//
//            // key的转换
//            Key key = new SecretKeySpec(keybytes, "AES");
//
//            // 加密
//            // AES/工作模式/填充方式
//            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//            cipher.init(Cipher.ENCRYPT_MODE, key);
//            byte[] result = cipher.doFinal(text.getBytes());
//            System.out.println("jdk aes encrypt : " + Base64.encodeBase64String(result));
//
//            // 解密
//            cipher.init(Cipher.DECRYPT_MODE, key);
//            result = cipher.doFinal(result);
//            System.out.println("jdk aes decrypt : " + new String(result));
//
//        } catch (Exception e) {
//            log.error(e);
//        }
//
//    }
}
